package com.dq.service.category.impl;

import com.alibaba.fastjson.JSONObject;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.CategoryQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import com.dq.domain.base.impl.BaseDaoImpl;
import com.dq.domain.category.Category;
import com.dq.domain.category.NullCategory;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.repository.BaseRepositories;
import com.dq.service.category.CategoryService;
import com.dq.utils.BeanNullUtil;
import com.dq.utils.TreeBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author heshuaijun
 * @date 2019/9/1715:20
 */
@Service
public class CategoryServiceImpl extends BaseRepositories implements CategoryService {

    @Override
    public Category save(Category category) {
       if(category.getParentCategory() == null) {
           throw new AdminException("上级类别为空");
       }

        SysUser loginUser = sysUserService.getUser();
        if(loginUser.getSection() == null || loginUser.getSection().getId() == null) {
            throw new AdminException("登录账号所属组织部门异常");
        }
        Category getCategory = categoryRepository.findByOrgAndTitleAndDeletedFalse(loginUser.getSection(), category.getTitle());
        if(getCategory != null && getCategory.getId() != null) {
            throw new AdminException("分类名称已存在");
        }

        if(category.getSortNo() == null) {
            category.setSortNo(1L);
        }
        category.setOrg(loginUser.getSection());
        category.setLevel(fmt(category.getParentCategory().getLevel()) + 1);

        category.setCreateUser(loginUser);
        category.setUpdateUser(loginUser);

        return categoryRepository.save(category);
    }

    @Override
    public Category update(Category updateCategory) {
        Category category = dao.get(Category.class, updateCategory.getId());
        if (category == null) {
            throw new AdminException("未找到此分类");
        }

        SysUser loginUser = sysUserService.getUser();
        Category getCategory = categoryRepository.findByOrgAndTitleAndDeletedFalse(loginUser.getSection(), updateCategory.getTitle());
        if(getCategory != null && !getCategory.getId().toString().equals(updateCategory.getId().toString())) {
            throw new AdminException("分类名称已存在");
        }

        BeanUtils.copyProperties(updateCategory, category, BeanNullUtil.getNullPropertyNames(updateCategory));

        return categoryRepository.save(category);
    }

    /**
     * 获取所有直属 下级子分类集合
     */
    @Override
    public List<Category> getParCategory(Long parentId) throws AdminException {
        Category category = dao.get(Category.class, parentId);
        if (null == category) {
            throw new AdminException("数据错误，没有此分类");
        }
        return categoryRepository.findByParentCategoryAndDeletedFalse(category);
    }

    /**
     * 获取所有下级
     */
    @Override
    public List<Category> getParCategoryAll(Long parentId) throws AdminException {
        List<Category> list = new ArrayList<>();
        while (true) {
            Category category = dao.get(Category.class, parentId);
            if (null == category) {
                throw new AdminException("数据错误，没有此分类");
            }
            List<Category> categoryList = categoryRepository.findByParentCategoryAndDeletedFalse(category);
            if(categoryList != null && categoryList.size() > 0) {
                list.addAll(categoryList);
            }else {
                break;
            }
            parentId = category.getId();
        }

        return list;
    }


    /**
     * 获取所有上级, 自身id
     */
    @Override
    public List<Category> getParCategoryList(Long sonid) throws AdminException {
        List<Category> list = new ArrayList<>();

        if(sonid != null) {
            while (true) {
                Category parCategory = dao.get(Category.class, sonid);
                if(parCategory != null) {
                    list.add(parCategory);
                    if(parCategory.getParentCategory() == null) {
                        break;
                    }else {
                        sonid = parCategory.getParentCategory().getId();
                    }
                }else {
                    break;
                }
            }
        }

        List<Category> list02 = new ArrayList<>();
        if(list.size() > 0) {
            for (int i = list.size()-1; i >= 0 ; i--) {
                Category category = list.get(i);
                if(!(category instanceof NullCategory)) {
                    list02.add(category);
                }
            }
        }

        return list02;
    }

    @Override
    public Vo getCategoryTree(CategoryQuery categoryQuery) throws AdminException {
        List<Category> categoryList = new ArrayList<>();
        List<Category.Vo> categoryVos = new ArrayList<>();
        /// 平台与门店都获取全部分分类
//        if (shiroService.isSuperAdmin()) {
//            categoryList = categoryRepository.findByDeletedIsFalseOrderBySortNoAsc();
//            categoryVos = TreeBuilder.buildCategoryTree((List<Category.Vo>) VO
//                    .toVOCollection(categoryList));
//        } else {
//            categoryList = categoryRepository.findByDeletedIsFalseAndOrgOrderBySortNoAsc(shiroService.getDept());
//            categoryVos = TreeBuilder.buildCategoryTree((List<Category.Vo>) VO
//                    .toVOCollection(categoryList));
//        }

        boolean t = false;
        Map<String, Object> query = categoryQuery.parseMap();
        query.remove("page");
        query.remove("size");
        if (StringUtils.isNotBlank(categoryQuery.getTitle())) {
            query.put("title" + BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(categoryQuery.getTitle()));
            query.remove("title");
            t = true;
        }
        if(categoryQuery.getParentCategoryId() != null) {
            query.put("parentCategory_id", categoryQuery.getParentCategoryId());
            query.remove("parentCategoryId");
            t = true;
        }

        categoryList = dao.find(dao.query2Hql(Category.class, query), query);
        if(t) {
            List<Category> sons = categoryRepository.findByParentCategoryInAndDeletedFalse(categoryList);
            categoryList.addAll(sons);
        }
        categoryVos = TreeBuilder.buildCategoryTree((List<Category.Vo>) VO.toVOCollection(categoryList));

        JSONObject json = new JSONObject();
        json.put("categoryTree", categoryVos);
        json.put("category", VO.toVOCollection(categoryList));
        return new Vo(json);
    }
}
